<template>
    <a-form ref="formRef" :model="fields" :label-col="labelWidth" :wrapper-col="{ span: wrapperCol }">
        <a-row>
            <template v-for="item in list" :key="item.field">
                <a-col v-if="!item.hidden" :span="item.col || 24">
                    <a-form-item v-if="item.type === 'slot'" :label-col="item.labelWidth" :label="item.label" :name="item.field" :rules="item.rules">
                        <slot :name="item.slotName" />
                    </a-form-item>
                    <a-form-item v-else :label-col="item.labelWidth" :label="item.label" :name="item.field" :rules="item.rules">
                        <component 
                            v-model="fields[item?.field]" 
                            v-model:val="fields[item?.field]" 
                            :is="components[item?.control]"
                            :placeholder="item.placeholder"
                            :options="item.options"
                            :disabled="item.disabled"
                            :maxlength="item.maxlength"
                            :name="item.name"
                            :min="item.min"
                            :max="item.max"
                            :width="item.width"
                            :config="item.config"
                            :optionsAsync="item.optionsAsync"
                            :mode="item.mode"
                            :id="item.id"
                            :rows="item.rows"
                            :showTime="item.showTime"
                            :valueFormat="item.valueFormat"
                            :defaultValue="item.defaultValue"
                        />
                    </a-form-item>
                </a-col>
            </template>
        </a-row>
    </a-form>
</template>
<script setup>
import { ref, computed } from "vue"
import components from "./components"
const props = defineProps({
    labelCol: {
        type: Number,
        default: 4
    },
    wrapperCol: {
        type: Number,
        default: 20
    },
    list: {
        type: Array,
        default: () => ([])
    },
    fields: {
        type: Object,
        defualt: () => ({})
    },
    styleCol: {
        type: [Object, String],
        default: ''
    }
})

// formRef
const formRef = ref(null)

/**
 * 校验表单
 */
const validataForm = () => {
    return new Promise((resolve, reject) => {
        formRef.value.validate().then(() => {
            resolve()
        }).catch(() => {
            reject()
        })
    })
}

/**
 * 校验表单
 */
const validateFields = (fields) => {
    formRef.value.validateFields(fields)
}

/**
 * 设置label的宽度
 */
const labelWidth = computed(() => props.styleCol || { span: props.labelCol })

defineExpose({
    validataForm,
    validateFields
})
</script>